package com.sample.kokou;

import java.sql.SQLException;

import com.j256.ormlite.android.apptools.OrmLiteBaseListActivity;
import com.j256.ormlite.dao.Dao;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;

public class DeletePerson implements OnItemLongClickListener {
	private OrmLiteBaseListActivity<SampleDBHelper> act;
	
	DeletePerson(OrmLiteBaseListActivity<SampleDBHelper> act) {
		this.act = act;
	}
	
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		confirmDeleteDialog(parent.getContext(), (int)id).show();
		return true;
	}

	private AlertDialog confirmDeleteDialog(Context context, final int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(R.string.confirm);
		builder.setMessage(R.string.confirm_deletion);
		builder.setPositiveButton(android.R.string.yes, 
            new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					Dao<Person, Integer> dao = act.getHelper().getDao(Person.class);
					Person person = dao.queryForId(id);
					dao.delete(person);
					act.setListAdapter(new PersonListAdapter(act, dao.queryForAll()));
				} catch (SQLException e) {
					throw new RuntimeException(e);
				}
			}
		});
		builder.setNegativeButton(android.R.string.no, null); 
		return builder.create();
	}
}
